<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.visitorName" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.visitReason" placeholder="来访事由" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <el-input v-model="listQuery.visitTime" placeholder="来访单位" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker
        type="datetimerange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />
      <el-input v-model="listQuery.title" placeholder="身份证信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.visitorPhone" placeholder="联系方式" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
       <el-table-column
      type="index"
      width="50">
      
    </el-table-column>
    <el-table-column label="来访时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTimeFormat }}至{{ row.endTimeFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访客姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.visitorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访客身份证" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.visitorIdCard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访客电话" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.visitorPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访客单位" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.visitorDept }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来访事宜" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.visitReason || '' }}</span>
        </template>
      </el-table-column>
      
      
      
      

      <el-table-column label="接待部门" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.respondentDeptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接待人" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.respondentName }}</span>
        </template>
      </el-table-column>
       <!-- <el-table-column label="签到时间" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.signTime || '' }}</span>
        </template>
      </el-table-column> -->
       <el-table-column label="预约状态" width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.status == '0'" type="info">未预约</el-tag>
          <el-tag v-if="row.status == '1'" >已预约待审核</el-tag>
          <el-tag v-if="row.status == '2'" type="success">审核通过</el-tag>
          <el-tag v-if="row.status == '3'" type="danger">审核不通过</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.reviewer }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="Imp" width="80px">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button> -->
          <!-- <el-button :disabled="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            审核
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            拒绝
          </el-button> -->
          <!-- <el-button size="mini" :disabled="row.status!='0'" type="primary" @click="handleCopy(row,$index)">
            复制申请链接
          </el-button> -->
          <el-button v-if="editable(row)" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-if="row.status=='2'&&row.signStatus<1" v-permission="['2']" size="mini" @click="handleSignIn(row)">签到</el-button>
          <el-button v-if="row.status=='2'&&row.signStatus==1"  v-permission="['2']" size="mini" @click="handleSignOut(row)">签退</el-button>
          <!-- <el-button v-if="row.status=='2'" size="mini" @click="showSignLog(row)">签到记录</el-button> -->
           <el-button size="mini" @click="showSignLog(row)">签到记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="同行人姓名" prop="accompanyMan">
          <el-input v-model="temp.accompanyMan" placeholder="同行人姓名,多人逗号分隔"/>
        </el-form-item>
        <el-form-item label="来访时间" prop="visitTime">
          <el-date-picker value-format="yyyyMMdd" type="daterange" v-model="temp.visitTime" />
        </el-form-item>
        <!-- <el-form-item label="预约状态" prop="status">
          <el-select v-model="temp.status">
            <el-option value="0" label="暂存" />
            <el-option value="1" label="预约" />
          </el-select>
        </el-form-item> -->

        <el-form-item  label="来访事由" prop="visitReason">
          <el-input v-model="temp.visitReason" />
        </el-form-item>
        <el-form-item  label="访客所属单位" prop="visitorDept">
          <el-input v-model="temp.visitorDept" />
        </el-form-item>
        <el-form-item  label="访客身份证" prop="visitorIdCard">
          <el-input v-model="temp.visitorIdCard" />
        </el-form-item>
        <el-form-item label="访客姓名" prop="visitorName">
          <el-input v-model="temp.visitorName" />
        </el-form-item>
        <!-- <el-form-item label="身份证" prop="idNumber">
          <el-input v-model="temp.title" />
        </el-form-item> -->
        <el-form-item label="访客电话" prop="visitorPhone">
          <el-input v-model="temp.visitorPhone" />
        </el-form-item>

 
        <el-form-item label="被访者公司编码" prop="respondentCompanyCode">
          <el-input v-model="temp.respondentCompanyCode" />
        </el-form-item>
        <el-form-item label="被访者公司名称" prop="respondentCompanyName" >
          <el-select v-model="temp.respondentCompanyName" @change="onChangeRespondentCompany">
            <el-option v-for="(org,idx) in orgList" :key="idx" :label="org.name" :value="org.name" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="被访者部门名称" prop="respondentDeptName">
          <el-input v-model="temp.respondentDeptName" />
        </el-form-item>
        <el-form-item label="被访者姓名" prop="respondentName">
          <el-input v-model="temp.respondentName" />
        </el-form-item>
               <el-form-item label="被访者电话" prop="respondentPhone">
          <el-input v-model="temp.respondentPhone" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button  @click="dialogStatus==='create'?createData({status:0}):updateData({status:0})">
          暂存
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData({status:1}):updateData({status:1})">
          预约
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">保存</el-button>
      </span>
    </el-dialog>


    <el-dialog :visible.sync="signLogVisable" title="签到记录">
      <el-table :data="signLog" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="signTime" label="时间" />
        <el-table-column label="动作" >
          <template slot-scope="{row,$index}">
            <div v-if="row.signType==1">签到</div>
            <div v-if="row.signType==2">签退</div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import {selectPage, createAppointment, saveAppointmentByLink, signOut, signUp, loadSignRecord} from "@/api/appointmentRecord"
import {getOrgListByCropId, loadCompany} from "@/api/org"
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission.js' // permission directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: undefined,
        // signStatus:""
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      orgList:[],
      signLogVisable : false,
      signLog : []
    }
  },
  created() {
    this.getList();
    this.loadOrgList();
  },
  methods: {
    editable (row){
      if(row.id == '9e5c45391ae381e001216e41c00f1fae'){
        console.log('id,userid',this.$store.getters.userId)
      }
      return row.status=='0' && row.creatorId==this.$store.getters.userId
    },
    showSignLog(row){
      console.log(row);
      this.signLogVisable = true ;
      this.loadSignLog(row)
    },
    loadSignLog({id}){
      loadSignRecord({id:id}).then(res=>{
        this.signLog = res.data.signRecords;
      })
    },
    loadOrgList(){
      loadCompany().then(res=>{
        this.orgList = res.data;
      })
    },
    onChangeRespondentCompany(item){
      console.log(item);
      const bm = this.orgList.filter(o=>o.name == item)[0].bianma
      this.temp.respondentCompanyCode = bm;
    },
    formatTimev2(time){
      const y = time.substring(0,4);
      const m = time.substring(4,6);
      const d = time.substring(6,8);

      return `${y}-${m}-${d}`
    },
    getList() {
      this.listLoading = true
      selectPage(this.listQuery).then(response => {
        
        this.list = response.data.records.map(item=>{
          
          item.startTimeFormat = item.startTime?this.formatTimev2(item.startTime):"";
          item.endTimeFormat = item.endTime?this.formatTimev2(item.endTime):"";
          item.visitTime=  [item.startTime,item.endTime];
          return item;
        })
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    async copyLink(link) {
      try {
        await navigator.clipboard.writeText(link);
        this.$message.success("链接已复制");
        this.copied = true;
        setTimeout(() => { this.copied = false; }, 2000);
      } catch (err) {
        console.error('复制失败:', err);
        // 降级方案
        this.fallbackCopyText(link);
      }
    },
    handleSignIn(data){
      const params= {id : data.id};
      signUp(params).then(res=>{
        const {success,msg} = res;
        if(success){
          this.$message.success("签到成功");
          this.getList();
        }else{
          this.$message.error("签到失败:",msg);
        }
      })
    },
    handleSignOut(data){
      const params= {id : data.id};
      signOut(params).then(res=>{
        const {success,msg} = res;
        if(success){
          this.$message.success("签出成功");
          this.getList();
        }else{
          this.$message.error("签出失败:",msg);
        }
      })
    },
    fallbackCopyText(text) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        this.copied = true;
        setTimeout(() => { this.copied = false; }, 2000);
      } catch (err) {
        console.error('降级复制失败:', err);
      }
      document.body.removeChild(textArea);
    },
    handleCopy(row){
        const url = `${process.env.VUE_APP_COPY_H5_URL}?id=${row.id}`
        console.log('copy',url);
        this.copyLink(url);
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        // status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData({status}) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
        //   this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
        //   this.temp.author = 'vue-element-admin'
          const temp = {
            ...this.temp,
            status,
            startTime : this.temp.visitTime[0],
            endTime : this.temp.visitTime[1]
          }
          createAppointment(temp).then(() => {
            // this.list.unshift(temp)
            this.dialogFormVisible = false
            this.getList();
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      console.log('onclickupdate',this.temp);
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData({status}) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          const temp = {
            ...tempData,
            status,
            startTime : tempData.visitTime[0],
            endTime : tempData.visitTime[1],
          }
          createAppointment(temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatTime(time){
      if(!time || time.length<=0){
        return time;
      }
      return `${time.substring(0,4)}-${time.substring(4,6)}-${time.substring(6,8)} ${time.substring(8,10)}:${time.substring(10,12)}`
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
